<?php
/**
 * User: PuLinGao
 * Date: 2014/12/21
 * 处理添加问卷导入网点信息Model
 */
class QuestionNetworkImportModel 
{
	private $buffer;
	private $error;
	
	private $titles = array(
		'network_name' => '网点名称',
		'network_num' => '网点编号',
		'up_network_num' => '上级编号',
		'level' => '网点级别',
		'network_username' => '网点登陆昵称',
		'network_pwd' => '网点登陆密码'
	);
	
	private $exclude_title = array(
		'分行编号','分行名称'
	);

	/**
	 * 设置错误信息，方便提示上传者
	 * @param type $errNo 错误单元格编号
	 * @param type $errMsg 错误信息
	 */
	private function setError($errNo, $errMsg){
		$this->error[] = array(
			'err_no' => $errNo,
			'err_msg' => $errMsg
		);
	}

	/**
	 * 获取错误信息
	 * @return type
	 */
	public function getError(){
		return $this->error;
	}
	
	/**
	 * 格式化excel数据
	 * @param type $question_id 问卷ID
	 * @param type $excelData	问卷excel数据
	 * @return boolean
	 */
	public function formatExcelData($excelData, $bank_id = null){
		if(empty($excelData)){
			$this->setError('base_1', "未获取到excel信息");
		}
		
		# 表头验证
		$dataTh = array_pop($excelData['data_th']);
		foreach ($dataTh as $key => $value) {
			if(!in_array($value['title'], $this->titles)){
				if(!in_array($value['title'], $this->exclude_title)){  // 排除一些不要的表头信息，如：分行编号，分行名称
					$this->setError($value['coordinate'], '“'.$value['title'].'” 与模板名称不一样，请仔细对照提供的网点导入下载模板');
				}
				unset($dataTh[$key]);
			}else{
				$titls_r = array_flip($this->titles);
				$dataTh[$key]['table_field'] = $titls_r[$value['title']];
			}
		}
		
		#表内容信息验证
		$levels = array();
		foreach (NetWork::networkLevel() as $key => $value) {
			$levels[$key] = $value['desc'];
		}
		
		foreach ($excelData['data'] as $key=>$data) {
			foreach ($data as $i => $v) {
				$dataTh[$i]['table_field'] and $this->buffer['network'][$key][$dataTh[$i]['table_field']] = $v['title']; # 对应数据库字段
				if ($bank_id) {
					$this->buffer['network'][$key]['bank_id'] = $bank_id;
				}
				
				if($v['title']){
					# 网点、上级编号、登录密码的验证(这里和目标列的属性有关系，不能修改模板) 去掉验证
//					if(in_array($i, array(1,4,6,7)) && !preg_match('/^[0-9a-zA-Z]\w*$/i', $v['title'])){
//						$this->setError($v['coordinate'], '“'.$dataTh[$i]['title'].'” 格式不正确，<b>请使用字母，数字，下划线的组合，不能以下划线开头或结尾</b>');
//					}
					
					# 登陆密码长度处理
					if ($dataTh[$i]['table_field'] == 'network_username' || $dataTh[$i]['table_field'] == 'network_pwd') {
	//					$this->buffer['network'][$key][$dataTh[$i]['table_field']] = md5($v['title']); 如果加密的话
						if (strlen($v['title']) > 30) {
							$this->setError($v['coordinate'], '“'.$dataTh[$i]['title'].'”太长了，最大长度不能超过30个字符');
						}
					}
					
					// 网点级别
					if($dataTh[$i]['table_field'] == 'level' ){
						
						$search = false;
						$gradeKey = 0;
						
						/**
						 * 1.二期修改特殊处理“竞争网点”，级别为5，只做入库操作，上级网点归类为“总行”
						 * 2.此处为什么需要单独验证【竞争网点】呢，为什么不使用in_array()的方式？
						 *   因为使用strstr的方式，有【网点】和【竞争网点】的存在，验证了【网点】 break，则【竞争网点】就不验证了，因此单独判断【竞争网点】
						 */
						$specialNet = NetWork::networkLevel();
						if ($v['title'] == $specialNet[NetWork::NETWORK_LEVEL_FIVE]['desc']) {
							$gradeKey = NetWork::NETWORK_LEVEL_FIVE;
							$search = true;
							
						}else{
							unset($levels[NetWork::NETWORK_LEVEL_FIVE]);
							foreach ($levels as $lekey => $val) {
								//如果定义的网点权限级别在填写文字中出现，就认为该网点是此级别
								if (false !== strstr($v['title'], $val)) {
									$gradeKey = $lekey;
									$search = true;
									break;
								}
							}
						}
						
						if(!$search){
							$this->setError($v['coordinate'], '“' . $dataTh[$i]['title'] . '” 下面的列中必须存在：“' . join(',', $levels) . '” 文字，否则将不能识别网点级别');
						}
						
						$this->buffer['network'][$key][$dataTh[$i]['table_field']] = $gradeKey;
						$this->buffer['network'][$key]['auth_grade'] = $gradeKey; # 网点权限对应网点等级
					}
				}else if($v['title'] === '' && $i<=5){ // 前几列的内容不能为空
					$this->setError($v['coordinate'], '“'.$dataTh[$i]['title'].'” 不能为空（如果	是总行，上级编号请填写0）');
				}
			}
		}
		
		# 提前保存Network， 验证上级网点
		$networkStatus = NetWork::model()->addImportNetwork($this->buffer['network']);
		if(!$networkStatus['ok']){
			foreach($networkStatus['msg'] as $key => $value){
				if(is_numeric($value)){
					continue;
				}
				
				# coordinate
				$coordinate = '';
				$oldFill = '';
				foreach ($this->buffer['network'][$key] as $i => $v) {
					if($i == 'up_network_num'){
						$oldFill = $v;
						foreach ($excelData['data'][$key] as $k => $d) {
							if($v == $d['title']){
								$coordinate = $d['coordinate'];
							}
						}
					}
				}
				$err_msg = $oldFill ? 'excel中的内容 “'.$oldFill.'” 对应的检查结果为：'.$value : $value;
				$this->setError($coordinate, $err_msg);
			}
		}
		
	}
	
	/**
	 * 保存数据，数据入库
	 * @param type $projectId
	 * @param type $questionId
	 * @return type
	 */
	public function saveExcelData($projectId, $questionId, $bank_id=null){
		if(!$projectId || !$questionId || !$this->buffer){
			return false;
		}
		
		# 保存NetworkQuestion
		$nqDatas = array();
		$networkData = array();
		foreach ($this->buffer['network'] as $value) {
			$networkData[] = NetWork::model()->find('network_num=:network_num and bank_id=:bank_id', array(':network_num'=> $value['network_num'],':bank_id' => $bank_id));
		}
		if($networkData){
			foreach ($networkData as $key => $network) {
				
				// 20140423需求，在插入network_question表时，默认只插入level=4(网点级别)的网点
				if ($network->level == Network::NETWORK_LEVEL_FOUR) {
					$nqDatas[] = array(
						'project_id' => $projectId,
						'network_id' => $network->network_id,
						'question_id' => $questionId,
						'network_name' => $network->network_name,
						'create_time' => time(),
						'update_time' => time(),
						'status' => -1,	# 20150509需求，默认添加问卷的时候问卷是草稿状态的，所以这时网点的问卷应该为暂停状态
					);
				}
			}
		}
		
		$return = NetworkQuestion::model()->addNetworkQuestion($projectId, $questionId, $nqDatas);
		
		# 更新问卷总数
        $return &= QuestionBase::model()->updateByPk($questionId, array('question_total' => count($networkData)));
		return $return;
	}
	
}